﻿using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;
using Microsoft.Extensions.Configuration;

namespace TestAdbCommand
{
    public class UserSecretsAESHelper
    {
        private string _appKey;
        private string _iv;
        private string _connectionString;

        public UserSecretsAESHelper()
        {
            LoadUserSecrets();
        }

        private void LoadUserSecrets()
        {
            try
            {
                // 使用ConfigurationBuilder读取UserSecrets
                var config = new ConfigurationBuilder()
                    .AddUserSecrets($"e67ad845-4b88-4662-9d66-34960dfb67d9")
                    .Build();
                
                // 获取配置信息
                _appKey = config["appKey"];
                _iv = config["IV"];
                _connectionString = config["MiTestEntities"];
                
                // 验证必要的配置是否存在
                if (string.IsNullOrEmpty(_appKey))
                {
                    throw new InvalidOperationException("appKey未在UserSecrets中配置");
                }
                
                if (string.IsNullOrEmpty(_iv))
                {
                    throw new InvalidOperationException("IV未在UserSecrets中配置");
                }
                
                if (string.IsNullOrEmpty(_connectionString))
                {
                    throw new InvalidOperationException("MiTestEntities未在UserSecrets中配置");
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"加载UserSecrets配置失败：{ex.Message}", ex);
            }
        }


        /// <summary>
        /// AES解密
        /// </summary>
        /// <param name="encryptStr">密文字符串</param>
        /// <returns>明文</returns>
        public string Decrypt(string encryptStr)
        {
            if (string.IsNullOrEmpty(_appKey) || string.IsNullOrEmpty(_iv))
            {
                throw new InvalidOperationException("appKey或IV未在UserSecrets中配置");
            }

            // 256-AES key    
            byte[] keyArray = UTF8Encoding.UTF8.GetBytes(_appKey);
            byte[] toEncryptArray = Convert.FromBase64String(encryptStr);

            RijndaelManaged rDel = new RijndaelManaged();
            rDel.Key = keyArray;
            rDel.Mode = CipherMode.ECB;
            rDel.Padding = PaddingMode.PKCS7;

            ICryptoTransform cTransform = rDel.CreateDecryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            return UTF8Encoding.UTF8.GetString(resultArray);
        }

        /// <summary>
        /// AES加密
        /// </summary>
        /// <param name="plainStr">明文字符串</param>
        /// <returns>密文</returns>
        public string Encrypt(string plainStr)
        {
            if (string.IsNullOrEmpty(_appKey) || string.IsNullOrEmpty(_iv))
            {
                throw new InvalidOperationException("appKey或IV未在UserSecrets中配置");
            }

            byte[] bKey = Encoding.UTF8.GetBytes(_appKey);
            byte[] bIV = Encoding.UTF8.GetBytes(_iv);
            byte[] byteArray = Encoding.UTF8.GetBytes(plainStr);

            string encrypt = null;
            Rijndael aes = Rijndael.Create();
            using (MemoryStream mStream = new MemoryStream())
            {
                using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateEncryptor(bKey, bIV), CryptoStreamMode.Write))
                {
                    cStream.Write(byteArray, 0, byteArray.Length);
                    cStream.FlushFinalBlock();
                    encrypt = Convert.ToBase64String(mStream.ToArray());
                }
            }
            aes.Clear();
            return encrypt;
        }

        /// <summary>
        /// 获取解密后的数据库连接字符串
        /// </summary>
        /// <returns>解密后的连接字符串</returns>
        public string GetDecryptedConnectionString()
        {
            if (string.IsNullOrEmpty(_connectionString))
            {
                throw new InvalidOperationException("MiTestEntities未在UserSecrets中配置");
            }

            return Decrypt(_connectionString);
        }

        /// <summary>
        /// 获取加密的数据库连接字符串
        /// </summary>
        /// <returns>加密的连接字符串</returns>
        public string GetEncryptedConnectionString()
        {
            if (string.IsNullOrEmpty(_connectionString))
            {
                throw new InvalidOperationException("MiTestEntities未在UserSecrets中配置");
            }

            return _connectionString;
        }

        /// <summary>
        /// 获取AppKey
        /// </summary>
        /// <returns>AppKey</returns>
        public string GetAppKey()
        {
            return _appKey;
        }

        /// <summary>
        /// 获取IV
        /// </summary>
        /// <returns>IV</returns>
        public string GetIV()
        {
            return _iv;
        }
    }
}